//
//  RequestHandler.swift
//  Solo
//
//  Created by JunMing on 2022/8/30.
//  Copyright © 2021 赵俊明. All rights reserved.
//

import Foundation
import Alamofire

// MARK: - RequestHandler & ResponseHandler
public class RequestHandler: RequestInterceptor {
    public var m_iRetryLimit: Int {
        return 2
    }
}

extension RequestHandler {
    public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
        var request: URLRequest = urlRequest
//        if let userid = SRUserManager.userid {
//            request.headers.add(HTTPHeader(name: "userid", value: userid))
//        }
//
//        if let appVersionString: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String {
//            request.headers.add(HTTPHeader(name: "AppVersion", value: appVersionString))
//        }
//
//        if excludeSendTokenWithAPI(urlRequest.url?.absoluteString) {
//            JMLogger.debug("exclude token: \(urlRequest.url?.absoluteString ?? "")")
//            SRUserManager.share.tokenHearders?.forEach { request.headers.add($0) }
//        }
        completion(.success(request))
    }
    
    private func excludeSendTokenWithAPI(_ url: String?) -> Bool {
        // 执行授权的URL列表
        let tokenList = ["user/login"] // .map { SRGloabConfig.share.doman.rawValue + $0 }
        return tokenList.contains(url ?? "")
    }
    
    public func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
        if (error.asAFError?.isResponseSerializationError ?? false) && request.response?.statusCode == 401 {
            completion(.doNotRetry)
            return
        }
        
        guard request.retryCount < m_iRetryLimit else {
            completion(.doNotRetry)
            return
        }
        
        switch request.response?.statusCode {
        case 401:
            // 如果
            if session.rootQueue.description.contains(NetManager.QueueType.Authorization.rawValue) {
                completion(.doNotRetry)
                
            } else {
                
            }
        default:
            completion(.doNotRetry)
        }
    }
}


// MARK: - 🈳️参数
public struct EmptyParameter: Encodable {
    public init() { }
}

extension DataRequest {
    @discardableResult
    public func reponseHandle(completionHandler: @escaping (AFDataResponse<Data>) -> Void) -> Self {
        return response(queue: .main, responseSerializer: ResponseHandler(), completionHandler: completionHandler)
    }
}
